const app = require('./config/koa');
const config = require('./config/db_config.json');
const query = require('./core/mysql');
const Store = require('./util/redis-store');
const draftSocket = require('./util/draft-socketio');
const redisMysql = require('./util/redis-mysql');
const session = require('koa-session2');
const http = require('http');
const fs = require('fs');
const path = require('path');
// var routes = require('./routes/index');
const logger = require('./core/logger').getLogger("system");

app.use(session({
  store: new Store(config.redis),
  ttl: 2 * 60 * 60 * 1000
}));

app.use(async(ctx, next) => {
  ctx.execSql = query;
  ctx.set('Access-Control-Allow-Origin', 'http://localhost:9003');
    // ctx.set('Access-Control-Allow-Origin', 'http://192.168.2.4:8080');
  await next();
});

fs.readdirSync(path.join(__dirname, 'routes')).forEach(function (file) {
    if (~file.indexOf('.js')) {
      app.use(require(path.join(__dirname, 'routes', file)).routes());
    }
});

app.use(function (ctx, next) {
    logger.info('not found api')
});

app.on('error', (error, ctx) => {
    logger.info('something error ' + JSON.stringify(ctx.onerror));
    logger.error('error ' + error);
});

const server = http.createServer(app.callback())
	.listen(process.argv.length > 3 ? process.argv[3] : config.port)
	.on('listening', function () {
	  let port =  process.argv.length > 3 ? process.argv[3] : config.port;
	  console.log('server listening on: ' + port);
  });

// 初始化websocket
draftSocket.initSocket(server);

// 初始化定时任务
redisMysql.redisToMysqlTask();
//F4jEAsk08C9RJ2zpMbwOqDCnJso1SqIYmakqvNRR/nL/z6mXOynAi2+G5YoTRs8OzaFsqgnwUaK6NQWx0oqrOQ==
